<!--
程序名：问卷填写页面
功能：用户打开问卷链接对问卷进行填写
-->
<template>
  <div class="display">
    <div class="content">
      <h3>{{ title }}</h3>
      <div class="top" v-if="description != ''">
        {{ description }}
      </div>

      <!--如果问卷发布中并且未过期-->
      <div v-if="status && dateJudge">
        <el-input v-model="sno" placeholder="请输入你的学号"></el-input>

        <el-card class="box-card" v-for="(item, index) in detail">
          <div slot="header" class="clearfix">
            <div class="questionTitle">
              <!--显示必填标识-->
              <span style="color: #f56c6c">
                <span v-if="item.must">*</span>
                <span v-else>&nbsp;</span>
              </span>
              {{ index + 1 + "." + item.title }}
            </div>
          </div>

          <!--单选题展示-->
          <div
            class="text item"
            v-if="item.type == 'radio'"
            v-for="optionItem in item.options"
          >
            <el-radio
              v-model="item.radioValue"
              :label="optionItem.id"
              style="margin: 5px"
              >{{ optionItem.title }}</el-radio
            >
          </div>

          <!--多选题展示-->
          <el-checkbox-group
            v-if="item.type == 'checkbox'"
            v-model="item.checkboxValue"
          >
            <div class="text item" v-for="optionItem in item.options">
              <el-checkbox :label="optionItem.id" style="margin: 5px">{{
                optionItem.title
              }}</el-checkbox>
            </div>
          </el-checkbox-group>

          <!--填空题展示-->
          <el-input
            v-if="item.type == 'text'"
            type="textarea"
            :rows="item.rowNum"
            v-model="item.textValue"
            resize="none"
          >
          </el-input>
        </el-card>

        <el-button type="primary" @click="submit">提交</el-button>
      </div>
    </div>

    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <span>该问卷未发布</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog title="提示" :visible.sync="dateVisible" width="30%">
      <span>该问卷已停止收集</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dateVisible = false">取 消</el-button>
        <el-button type="primary" @click="dateVisible = false">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="mustTitle"
      :visible.sync="mustShow"
      :close-on-click-modal="false"
      class="dialog"
    >
      <div style="color: #42a5f5; font-size: 250%">有必做题未做！</div>
      <div style="width: 100%; text-align: right">
        <el-button style="margin-left: 10px" @click="mustShow = false"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import axios from "axios";
export default {
  data() {
    return {
      mustShow: false,
      sno: "",
      dateVisible: false,
      dialogVisible: false,
      dialogTitle: "",
      title: "",
      description: "",
      finishDate: "",
      status: "",
      dateJudge: "",
      detail: [],
      formId: 0,
      fillForm: [],
      answer_item: {},
      mustTitle: "提示",
    };
  },
  mounted() {
    this.formId = this.$route.params.id;
    console.log(this.formId);

    this.getForm(this.formId);
  },
  methods: {
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    dateFormat(fmt, date) {
      let ret;
      const opt = {
        "Y+": date.getFullYear().toString(), // 年
        "m+": (date.getMonth() + 1).toString(), // 月
        "d+": date.getDate().toString(), // 日
        "H+": date.getHours().toString(), // 时
        "M+": date.getMinutes().toString(), // 分
        "S+": date.getSeconds().toString(), // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      };
      for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
          fmt = fmt.replace(
            ret[1],
            ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
          );
        }
      }
      return fmt;
    },
    //比较日期，看问卷是否过期
    compareDate(finishDate) {
      var dateNow = new Date();
      var finish = new Date(finishDate);
      if (finish.getTime() > dateNow.getTime()) {
        this.dateJudge = true;
      } else {
        this.dateJudge = false;
      }
    },
    //根据id获取表单，并判断表单状态
    getForm(id) {
      const _this = this;
      axios
        .get("http://localhost:8082/userForm/findById/" + id)
        .then(function (resp) {
          _this.title = resp.data.title;
          _this.description = resp.data.description;
          _this.finishDate = resp.data.finishDate;
          _this.status = resp.data.status;
		  //问卷是否已发布
          if (_this.status) {
            //看问卷是否过期
            _this.compareDate(_this.finishDate);
			//如果没过期
            if (_this.dateJudge) {
              _this.detail = resp.data.questions;
				
				//给数据添加属性
              for (let i = 0; i < _this.detail.length; i++) {
                _this.$set(_this.detail[i], "radioValue", -1);
                _this.$set(_this.detail[i], "checkboxValue", []);
                _this.$set(_this.detail[i], "textValue", "");
              }
            } else {
              _this.dateVisible = true;   //问卷已过期
            }
          } else {
            _this.dialogVisible = true;   //问卷未发布
          }

          console.log(JSON.stringify(_this.detail));
        })
        .catch(function (error) {
          console.log(error);
        });
    },

    //获取用户的填写信息
    getFillForm() {
      for (let i = 0; i < this.detail.length; i++) {
        let fillDate = this.dateFormat("YYYY-mm-dd HH:MM", new Date());

        if (this.detail[i].type == "radio") {
          let answer_item = {};

          // answer_item.user_id = this.userId;
          answer_item.form_id = this.formId;
          answer_item.user_id = this.sno;
          answer_item.question_id = this.detail[i].id;
          answer_item.fillDate = fillDate;
          answer_item.answer = this.detail[i].radioValue;
          this.fillForm.push(answer_item);
        } else if (this.detail[i].type == "checkbox") {
          for (let j = 0; j < this.detail[i].checkboxValue.length; j++) {
            let answer_item = {};

            answer_item.form_id = this.formId;
            answer_item.user_id = this.sno;
            answer_item.question_id = this.detail[i].id;
            answer_item.fillDate = fillDate;
            answer_item.answer = this.detail[i].checkboxValue[j];
            this.fillForm.push(answer_item);
            //answer1 = answer1 + "_" + this.detail[i].checkboxValue[j];
          }
        } else if (this.detail[i].type == "text") {
          let answer_item = {};
          // answer_item.user_id = this.userId;
          answer_item.form_id = this.formId;
          answer_item.user_id = this.sno;
          answer_item.question_id = this.detail[i].id;
          answer_item.fillDate = fillDate;
          answer_item.answer = this.detail[i].textValue;
          this.fillForm.push(answer_item);
        }
      }
    },
    judgeMust() {
      for (let index = 0; index < this.detail.length; index++) {
        if (this.detail[index].must) {
          if (this.detail[index].type == "radio") {
            if (this.detail[index].radioValue == -1) {
              return false;
            }
          } else if (this.detail[index].type == "checkbox") {
            if (this.detail[index].checkboxValue.length == 0) {
              return false;
            }
          } else if (this.detail[index].type == "text") {
            if (this.detail[index].textValue == "") {
              return false;
            }
          }
        }
      }
      return true;
    },
    //提交问卷
    submit() {
      console.log(this.judgeMust());
      this.$confirm("确定提交问卷?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        if (!this.judgeMust()) {
          this.mustShow = true;
        } else {
          this.getFillForm();

          let datas = JSON.stringify(this.fillForm);
          console.log(datas);
          const _this = this;

          axios({
            method: "post",
            url: "http://localhost:8082/fillForm/save",
            headers: {
              "Content-Type": "application/json",
            },
            data: datas,
          }).then(function (resp) {
            _this.$router.push({
              path: "/thankyou",
            });
          });
        }
      });
    },
  },
};
</script>
<style scoped>
.display {
  text-align: center;
  padding: 20px;
}

.display .top {
  color: #606266;
  padding: 0 10px 10px 10px;
  border-bottom: 3px solid #409eff;
  font-size: 15px;
  line-height: 22px;
  text-align: left;
}

.display .content {
  width: 100%;
  max-width: 800px;
  display: inline-block;
  text-align: center;
}

.display .box-card {
  text-align: left;
  width: 100%;
  margin: 10px 0 10px 0;
}

.display .bottom {
  margin: 20px 10px 20px 10px;
  color: #909399;
}

.display a:link,
a:visited,
a:active {
  color: #909399;
  text-decoration: none;
}
</style>
